package com.tiantian.subject.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tiantian.common.core.constant.SystemConfigConstants;
import com.tiantian.common.core.domain.dto.AnswerTimeDAO;
import com.tiantian.common.core.exception.BusinessException;
import com.tiantian.common.core.utils.DateUtils;
import com.tiantian.common.redis.utils.RedisUtils;
import com.tiantian.common.satoken.utils.FieldUtils;
import com.tiantian.common.satoken.utils.LoginHelper;
import com.tiantian.subject.domain.entity.UserSolve;
import com.tiantian.subject.mapper.UserSolveMapper;
import com.tiantian.subject.service.UserSolveService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * (SysReplay表)服务实现类
 *
 * @author tiantian
 */
@Service
@RequiredArgsConstructor
public class UserSolveServiceImpl implements UserSolveService {

    private final UserSolveMapper userSolveMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param replyId 主键
     * @return 实例对象
     */
    @Override
    public UserSolve selectById(String replyId) {
        UserSolve userSolve = userSolveMapper.selectById(replyId);
        if (ObjectUtil.isNull(userSolve)) {
            throw new BusinessException(StrUtil.format("答题记录不存在,topicId:{}", replyId));
        }
        return userSolve;
    }

    /**
     * 根据条件查询
     *
     * @return 实例对象的集合
     */
    @Override
    public List<UserSolve> selectList(UserSolve userSolve) {
        return userSolveMapper.selectList(userSolve);
    }

    /**
     * 新增数据
     */
    @Override
    public Boolean insert(UserSolve userSolve) {
        // 判断当前提交时间是否在允许提交范围内
        checkTimeRange();
        // 判断题目是否存在
        String topicId = userSolve.getTopicId();
        // 判断用户是否已经提交
        Long userId = LoginHelper.getUserId();
        if (checkReplyUnique(topicId, userId) > 0) {
            throw new BusinessException("请勿重复提交该题目");
        }
        // 属性设置
        String replyId = IdUtil.getSnowflakeNextIdStr();
        userSolve.setReplyId(replyId);
        userSolve.setScore(-1);
        userSolve.setJudger(null);
        userSolve.setUserId(userId);
        // 设置基础字段
        FieldUtils.insertAndSetCommonFields(userSolve);
        return userSolveMapper.insert(userSolve);
    }

    /**
     * 修改数据
     */
    @Override
    public Boolean changAnswer(UserSolve userSolve) {
        // 判断当前提交时间是否在允许修改范围内
        checkTimeRange();
        String topicId = userSolve.getTopicId();
        // 判断题目是否存在
        Long userId = LoginHelper.getUserId();
        // 判断是否有答题记录
        int count = checkReplyUnique(topicId, userId);
        if (count == 0) {
            throw new BusinessException("修改答案失败,无任何作答记录");
        }
        // 设置字段
        userSolve.setUserId(userId);
        FieldUtils.updateCommonFields(userSolve);
        return userSolveMapper.updateAnswer(userSolve);
    }

    /**
     * 删除工作人员答题记录
     */
    @Override
    public Boolean deleteAdminReplys() {
        userSolveMapper.deleteAdminReplys();
        return true;
    }

    @Override
    public int checkReplyUnique(String topicId, Long userId) {
        return userSolveMapper.checkReplyUnique(topicId, userId);
    }


    @Override
    public String selectAnsByTopicIdAndUserId(String topicId, Long userId) {
        return userSolveMapper.selectAnsByTopicIdAndUserId(topicId, userId);
    }

    @Override
    public int updateByReplyId(UserSolve userSolve) {
        return userSolveMapper.updateByReplyId(userSolve);
    }

    @Override
    public int countReply(Long userId) {
        return userSolveMapper.countReplyByUserId(userId);
    }

    @Override
    public List<UserSolve> selectByUserId(Long userId) {
        return userSolveMapper.selectByUserId(userId);
    }

    /**
     * 检查提交时间是否符合系统设置的时间
     */
    private void checkTimeRange() {
        // 获取系统设置的时间
        AnswerTimeDAO ansTime = RedisUtils.getCacheObject(SystemConfigConstants.SYSTEM_CONFIG_ANSWER_TIME_KEY);
        if (ObjectUtil.isEmpty(ansTime)) {
            throw new BusinessException("答题时间未设置请联系管理员");
        }
        // 获取当前时间
        LocalDateTime localDateTimeNow = DateUtils.getCurrentDateTime();

        // 构造开始时间和结束时间
        LocalDateTime startTime = LocalDateTimeUtil.parse(ansTime.getDate() + " " + ansTime.getStart(), "yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTimeUtil.parse(ansTime.getDate() + " " + ansTime.getEnd(), "yyyy-MM-dd HH:mm:ss");

        // 判断是否在答题时间范围内
        if (!(localDateTimeNow.isAfter(startTime) && localDateTimeNow.isBefore(endTime))) {
            throw new BusinessException("当前时间不在答题时间范围内");
        }
    }

}


